package cn.xu.study.lucene.getstarted;

import org.apache.commons.io.FileUtils;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.junit.Test;

import java.io.File;

public class LuceneDemo {
    private String INDEX_PATH = "D:\\idea_boxuegu\\temp\\lucenepath\\lucene_index";    //索引存储路径
    private String SOURCE_PATH = "D:\\idea_boxuegu\\temp\\lucenepath\\sourcefile";    //原始文档的存放路径。doc目录下有测试数据，把测试数据文件复制到SOURCE_PATH路径下

    @Test
    public void createIndex() throws Exception{
        //第一步：创建一个indexwriter对象。
        //1）指定索引库的存放位置Directory对象
        Directory directory = FSDirectory.open(new File(INDEX_PATH).toPath());
        //2）指定一个IndexWriterConfig对象。
        IndexWriterConfig indexWriterConfig = new IndexWriterConfig();
        IndexWriter indexWriter = new IndexWriter(directory, indexWriterConfig);
        //第二步：创建document对象。本案例中搜索来自磁盘的文件。遍历指定路径下所有文件，挨个创建document对象
        File file = new File(SOURCE_PATH);
        if (file.isDirectory()){
            for (File iteratorFile : file.listFiles()){
                //1)获取数据，创建域。
                String fileName = iteratorFile.getName();
                String fileContent = FileUtils.readFileToString(iteratorFile);
                Field fileNameField = new TextField("filename", fileName, Field.Store.YES);
                Field fileContentField = new TextField("filecontent", fileContent, Field.Store.YES);
                //2)创建document对象
                Document document = new Document();
                //3)域添加进文档对象
                document.add(fileNameField);
                document.add(fileContentField);
                //4)创建索引，并写入索引库
                indexWriter.addDocument(document);
            }
        }
        //关闭indexwriter
        indexWriter.close();
    }

    @Test
    public void searchIndex(){

    }
}
